<?php

namespace App\Http\Middleware;

use App\Admin;
use Closure;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;

class ClearanceMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
//        $user = Admin::find(1);
//        if ( !$user->hasPermissionTo('all') ) // 用户是否all权限
//        {
//            //获取当前路由名称
//            $route_name = $request->route()->getName();
//            if (!$user->hasPermissionTo($route_name)) {
//                return response()->json(['code'=>4,'msg'=>'no auth']);
//            }
//        }
//        echo '<pre>';
//        $permissionNames  =  $user->getPermissionsViaRoles(); //根据角色获取用户所有权限
//        $permissionNames  =  $user->getAllPermissions(); //根据角色获取用户所有权限
//        //获取用户角色的名称
//        $roles  =  $user -> getRoleNames();
//        var_dump(json_decode($roles));exit;
//        return $next($request);
//        echo '<pre>';
//        var_dump($user);exit;
        //var_dump($roles = Auth::guard('admin')->user()->roles()->pluck('id'));exit;
        $user = Auth::guard('admin')->user();
        if ( !$user->hasPermissionTo('all') ) // 用户是否all权限
        {
            //获取当前路由名称
            $route_name = $request->route()->getName();
            if (!$user->hasPermissionTo($route_name)) {
                return response()->json(['code'=>4,'msg'=>'no auth']);
            }
        }
        echo '<pre>';
        $permissionNames  =  $user->getPermissionsViaRoles(); //根据角色获取用户所有权限
        $permissionNames = json_decode($permissionNames,true);
        print_r($permissionNames);exit;
        return $next($request);
    }

    private function get_menu($list,$p_id=0){
        $tree = [];
        foreach($list as $k=>$v){
            $arr = [];
            if($v['p_id'] == $p_id){
                $arr['title'] = $v['title'];
            }
        }
    }
}
